import Point from '../../Point.js';
import * as utils from './utils.js';

/**
 * Matrix
 */
export function create(el, dimensions, padding, ratio = 1) { //eslint-disable-line
    // console.log('[Matrix] create: ', dimensions, ratio);
    let width = parseInt(el.width, 10),
        height = parseInt(el.height, 10),
        xMin = dimensions[0],
        xMax = dimensions[1],
        yMin = dimensions[2],
        yMax = dimensions[3],
        p = (100 - (typeof padding !== 'undefined' ? padding : 10)) / 100,
        scale = Math.min((width * p) / (xMax - xMin), (height * p) / (yMax - yMin)),
        offsX = width / 2 - (scale * (xMax - xMin)) / 2 - scale * xMin,
        offsY = height / 2 + (scale * (yMax - yMin)) / 2 + scale * yMin;
    if (!offsX){
        offsX = 0;
    }
    if (!offsY) {
        offsY = 0;
    }
    // let matrix = new DOMMatrix();
    let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
        matrix = svg.createSVGMatrix();

    matrix = matrix.translate(offsX * ratio, offsY * ratio);
    matrix = matrix.scale(scale * ratio);
    matrix = matrix.flipY();
    // console.log('[Matrix] create: ', matrix);
    return matrix;
}

export function getTranslation(matrix) {
    return new Point(matrix.e, matrix.f);
}

export function getRotation(matrix) {
    return degrees(Math.atan2(-matrix.b, matrix.a));
}

export function getScaling(matrix) {
    if (!matrix) return null;
    var sx = Math.sqrt(matrix.a * matrix.a + matrix.b * matrix.b);
    var sy = Math.sqrt(matrix.c * matrix.c + matrix.d * matrix.d);

    return new Point(sx, sy);
}

export function degrees(value) {
    value *= 180 / Math.PI;
    if (value < 0) value += 360;
    if (value > 360) value -= 360;
    return value;
}

export function getPixelRatio(context) { //eslint-disable-line
    let backingStore =
        context.backingStorePixelRatio ||
        context.webkitBackingStorePixelRatio ||
        context.mozBackingStorePixelRatio ||
        context.msBackingStorePixelRatio ||
        context.oBackingStorePixelRatio ||
        context.backingStorePixelRatio ||
        1;
    if (utils.isMobile()) return 1;
    return 2 / backingStore;
    // // let rtn = (window.devicePixelRatio || 1) / backingStore;
    // // if (!rtn) rtn = 2;
    // // return (window.devicePixelRatio || 1) / backingStore;
    // console.log('[Matrix] getPixelRatio: ', backingStore);
    // return 1;
}
